Imports System.Web.UI
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Linq

Imports DotNetNuke
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Services.Localization
Imports DotNetNuke.UI.Utilities

Imports DotNetNuke.Entities.Content.Taxonomy
Imports DotNetNuke.Entities.Content

Namespace Modules.Quicksand

    <ControlMethodClass("OliverHine.Modules.Quicksand.ViewQuicksand")> _
    Partial Class ViewQuicksand
        Inherits AjaxPortalModuleBase
        Implements Entities.Modules.IActionable

#Region "Properties"

        Private ReadOnly Property TagVocabulary() As Vocabulary
            Get
                Dim vocabularyController As New VocabularyController()
                Return (From v In vocabularyController.GetVocabularies() _
                       Where v.IsSystem AndAlso v.Name = "Tags" _
                       Select v) _
                       .SingleOrDefault()
            End Get
        End Property

        Private ReadOnly Property ParentTabId As Integer
            Get
                If Settings.ContainsKey("ParentTabID") AndAlso String.IsNullOrEmpty(Settings("ParentTabID").ToString()) = False Then
                    Return Integer.Parse(Settings("ParentTabID").ToString())
                Else
                    Return PortalSettings.ActiveTab.TabID
                End If
            End Get
        End Property

        Private ReadOnly Property ShowHiddenTabs As Boolean
            Get
                If Settings.ContainsKey("ShowHiddenTabs") Then
                    Return Boolean.Parse(Settings("ShowHiddenTabs").ToString)
                Else
                    Return False
                End If
            End Get
        End Property

        Private ReadOnly Property ParentPortalId As Integer
            Get
                If ParentTabId = PortalSettings.ActiveTab.TabID Then
                    If PortalSettings.ActiveTab.IsSuperTab Then
                        Return -1
                    End If
                Else
                    Dim objTabs As New TabController
                    Dim objTab As Entities.Tabs.TabInfo = objTabs.GetTab(ParentTabId, Null.NullInteger, True)
                    If objTab IsNot Nothing Then
                        If objTab.IsSuperTab Then
                            Return -1
                        End If
                    End If
                End If

                Return PortalId
            End Get
        End Property


#End Region

#Region "AjaxPortalModuleBase Events"
        '-------------------------------------------------------------------------------------------------------------
        '- This is where you add your custom properties that are to be sent down to the client-side object
        '- By default we are passing the naming container ID (ns) and localized messages (msgs) 
        '- If you add your own properties make sure you update your client code with those properties found in EditQuicksand.ascx.js
        '-      get_ImagePath: function() {return this._imagePath;},
        '-      set_ImagePath: function(value) {this._imagePath = value;},
        '-------------------------------------------------------------------------------------------------------------
        Protected Sub AjaxPortalModuleBase_AddScriptComponentDescriptors(ByVal Descriptor As ScriptComponentDescriptor) Handles MyBase.AddScriptComponentDescriptors
            'IMPORTANT!  Enter Client Namespace + ObjectName as Type
            Descriptor.Type = "OliverHine.ViewQuicksand"

            '---------------------------------------------------------------------------------------------------------
            'Add custom properties here
            '   Descriptor.AddScriptProperty("ImagePath", String.Format("'{0}'", Me.ModulePath & "images/"))
            '---------------------------------------------------------------------------------------------------------
        End Sub

        '-------------------------------------------------------------------------------------------------------------
        '- This is where your client-side javascript that uses the MS AJAX framework needs to be registered
        '- Adding the reference here ensures that the MS AJAX script is run before our script which uses things like Type.registerNamespace run
        '-------------------------------------------------------------------------------------------------------------
        Protected Sub AjaxPortalModuleBase_AddScriptReferences(ByVal References As List(Of ScriptReference)) Handles MyBase.AddScriptReferences
            
            If DotNetNuke.Framework.jQuery.UseDebugScript = True Then
                References.Add(New System.Web.UI.ScriptReference(Me.ControlPath & "ViewQuicksand.ascx.js"))

                References.Add(New System.Web.UI.ScriptReference(Me.ControlPath & "js/jquery.easing.1.3.js"))
                References.Add(New System.Web.UI.ScriptReference(Me.ControlPath & "js/jquery-css-transform.js"))
                References.Add(New System.Web.UI.ScriptReference(Me.ControlPath & "js/jquery-animate-css-rotate-scale.js"))

                References.Add(New System.Web.UI.ScriptReference(Me.ControlPath & "js/jquery.quicksand.js"))
            Else

                References.Add(New System.Web.UI.ScriptReference(Me.ControlPath & "ViewQuicksand.min.js"))
            End If

        End Sub

        '-------------------------------------------------------------------------------------------------------------
        '- Add any localized text needed on the client
        '-------------------------------------------------------------------------------------------------------------
        Protected Sub AjaxPortalModuleBase_AddLocalizedMessages(ByVal Messages As Dictionary(Of String, String)) Handles MyBase.AddLocalizedMessages
            Messages("btnHello") = Localization.GetString("btnHello.Client", LocalResourceFile)
        End Sub

#End Region

#Region "Event Handlers"

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try
                DotNetNuke.Framework.jQuery.RequestRegistration()

                litActions.Text = DisplayTags(ParentTabId)
                lblResponse.Text = DisplayPages(ParentTabId)

            Catch exc As Exception        'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

#End Region

        Private Function DisplayTags(ByVal iTabId As Integer) As String
            Dim strWrapper As String = "<ul id=""{2}_actions"" class=""splitter""><li>Filter by tag: <ul>{0}</ul></li><li style=""display:none;""><img id=""{2}_imgAjax"" src=""" & Me.ResolveUrl("ajaxanim.gif") & """ /></li></ul>"
            Dim strItem As String = "<li class=""{2}""><a href=""#"" data-id=""tagid-{0}"">{1}</a></li>"

            Dim lstTabs As List(Of Entities.Tabs.TabInfo) = GetTabs(iTabId)

            Dim lstTerms As New List(Of Term)

            If lstTabs.Count > 0 Then
                'we have some pages

                Dim objTermId As Integer
                For Each objTab As Entities.Tabs.TabInfo In lstTabs
                    'loop through each page
                    For Each objTerm As Term In objTab.Terms
                        'then loop through each term / tag
                        objTermId = objTerm.TermId
                        If lstTerms.Any(Function(term) term.TermId = objTermId) = False Then
                            lstTerms.Add(objTerm)
                        End If
                    Next
                Next

                If lstTerms.Count > 0 Then


                    Dim sb As New Text.StringBuilder

                    Dim iCounter As Integer = 1
                    Dim css As String = String.Empty
                    For Each objTerm As Term In lstTerms
                        If iCounter = 1 Then
                            css = "segment-1"
                        Else
                            css = "segment-0"
                        End If
                        sb.AppendFormat(strItem, objTerm.TermId, objTerm.Name, css)

                        iCounter = iCounter + 1
                    Next

                    sb.AppendFormat(strItem, "-1", "All", "segment-2")

                    'Dim sbSort As New Text.StringBuilder
                    'sbSort.AppendFormat(strItem, "-2", "Name", "segment-1")
                    'sbSort.AppendFormat(strItem, "-3", "View Order", "segment-2")

                    Return String.Format(strWrapper, sb.ToString(), String.Empty, Me.ClientID)

                End If
            End If

            Return String.Empty

        End Function

        Private Function DisplayPages(ByVal iTabId As Integer, Optional ByVal TagId As Integer = -1) As String
            Dim strWrapper As String = "<ul class=""quicksand"">{0}</ul>"
            Dim strItem As String = "<li data-id=""tabid-{0}""><a href=""{3}""><img src=""{1}"" /><strong>{2}</strong></a></li>"

            Dim lstTabs As List(Of Entities.Tabs.TabInfo) = GetTabs(iTabId)
            
            If lstTabs.Count > 0 Then
                'we have some tabs

                If Null.IsNull(TagId) = False Then
                    'filter the list for the TagId
                    lstTabs = (From a In lstTabs Where a.Terms.Any(Function(tag) tag.TermId = TagId)).ToList()
                End If

                Dim sb As New Text.StringBuilder
                For Each objTab In lstTabs
                    If String.IsNullOrEmpty(objTab.IconFileLarge) Then
                        'no image
                        sb.AppendFormat(strItem, objTab.TabID, Me.ResolveUrl("~/images/icon_unknown_32px.gif"), objTab.TabName, NavigateURL(objTab.TabID))
                    Else
                        'has an image
                        sb.AppendFormat(strItem, objTab.TabID, Me.ResolveUrl(objTab.IconFileLarge), objTab.TabName, NavigateURL(objTab.TabID))
                    End If

                Next

                Return String.Format(strWrapper, sb.ToString())
            End If

            Return String.Empty
        End Function

        Private Function GetTabs(ByVal iTabId As Integer) As List(Of Entities.Tabs.TabInfo)
            Dim lstTabs As List(Of Entities.Tabs.TabInfo) = Tabs.TabController.GetTabsByParent(iTabId, ParentPortalId)

            If ShowHiddenTabs = False Then
                lstTabs = (From a In lstTabs Where a.IsVisible = True Select a).ToList()
            End If

            Return lstTabs
        End Function

#Region "Control Methods"
        '-------------------------------------------------------------------------------------------------------------
        '- Exposing methods to the client code is as simple as adding the ControlMethod attribute
        '- IMPORTANT!   ALWAYS SECURE YOUR CONTROL METHODS IF INTERACTING WITH SENSITIVE DATA
        '-------------------------------------------------------------------------------------------------------------
        <ControlMethod()> _
        Public Function FetchPages(ByVal TagId As String) As String
            If TagId.Contains("tagid-") Then
                TagId = TagId.Replace("tagid-", String.Empty)

                If IsNumeric(TagId) Then

                    Return DisplayPages(ParentTabId, Integer.Parse(TagId))

                End If
            End If

            Return DisplayPages(ParentTabId)
        End Function
#End Region


#Region "Optional Interfaces"

        ' Registers the module actions required for interfacing with the portal framework
        Public ReadOnly Property ModuleActions() As Entities.Modules.Actions.ModuleActionCollection Implements Entities.Modules.IActionable.ModuleActions
            Get
                Dim Actions As New Entities.Modules.Actions.ModuleActionCollection
                Actions.Add(GetNextActionID(), Localization.GetString("Edit.Text", LocalResourceFile), Entities.Modules.Actions.ModuleActionType.AddContent, "", "", EditUrl(), False, Security.SecurityAccessLevel.Edit, True, False)
                Return Actions
            End Get
        End Property

#End Region

    End Class

End Namespace
